<template>
  <div v-if="props.mode === 'detail'">
    <span>{{ textValue }}</span>
  </div>
  <el-input
    v-else
    ref="inputRef"
    v-bind="defaultAttr"
    readonly
    :prefix-icon="Search"
    v-model.trim="textValue"
    style="width: 100%"
    @change="handleChange"
    @focus="handleFocus"
  >
  </el-input>
  <template v-if="props.mode !== 'detail'">
    <Teleport to="#app">
      <table-dialog
        ref="tableDialogRef"
        :columns="props.config.columns"
        :dataSource="props.config.dataSource"
        :otherQuery="otherQuery"
        :rowKey="props.config.rowKey"
        @close="handleLoseFocus"
        @check="handleCheck"
      />
    </Teleport>
  </template>
</template>

<script setup>
import TableDialog from '@/components/TableDialog.vue'
import { Search } from '@element-plus/icons-vue'
import { nextTick, reactive } from 'vue'
// v-model值
const modelValue = defineModel()
const textValue = defineModel('text')

// 输入框配置项
const props = defineProps({
  config: {
    type: Object,
    default: () => {},
  },
  mode: {
    // 'edit' | 'detail' | 'add'
    type: String,
    default: 'detail',
  },
  form: {
    type: Object,
    default: () => {},
  },
})

const defaultAttr = computed(() => {
  // 设置默认绑定值
  let { attrs = {} } = props.config
  // 获取默认项
  attrs['placeholder'] = attrs?.placeholder || `请输入${props.config.label}`

  // 判断禁用
  attrs['disabled'] = props.config?.disabled || false
  if (props?.config?.linkage) {
    otherQuery.value = props.form
  }
  return { ...attrs }
})

// 监听data
const otherQuery = reactive({})
watch(
  () => ({ ...props.form }),
  (newVal, oldVal) => {
    if (props.config.linkage) {
      const linkage = props.config.linkage
      if (typeof linkage === 'string' && newVal[linkage] && newVal[linkage] !== oldVal[linkage]) {
        otherQuery.value = { ...props.form }
      } else if (Array.isArray(linkage) && linkage.some((i) => newVal[i] && newVal[i] !== oldVal[i])) {
        otherQuery.value = { ...props.form }
      }
    }
  },
  { deep: true }
)

// 事件
const emits = defineEmits(['change'])
const handleChange = (value) => {
  if (props.config.event) {
    emits('change', value)
  }
}
const handleCheck = (val) => {
  modelValue.value = val[props.config.rowKey || 'id']
  textValue.value = val[props.config.textKey || props.config.rowKey]
  handleChange(val)
  // if(props.options.defaultName){

  // }
}

// 弹窗
const tableDialogRef = ref(null)
const inputRef = ref(null)
const handleFocus = () => {
  tableDialogRef.value.open()
}
const handleLoseFocus = () => {
  nextTick(() => {
    inputRef.value.blur()
  })
}
</script>

<style lang="scss" scoped>
.suffix {
  color: var(--el-input-icon-color, var(--el-text-color-placeholder));
  transition: all var(--el-transition-duration);
  pointer-events: none;
  margin-left: 8px;
}
</style>
